<!--
 * @Date: 2022-06-15 17:41:02
 * @Author: 陶子
 * @LastEditTime: 2023-07-05 14:48:16
 * @FilePath: \jk_one-stop_cloud_mobile_v1.0\src\views\warehouseManagement\goodsManagement\goodsManagementAdd.vue
 * @pageName: 这是--(物品新建||编辑)--页面
-->
<template>
  <div>
    <Navbar :appTitle="appTitle" />
    <div class="search-content wrap-apply"
      :style="{top: GLOBAL.currentEnvironment ? '0' : '',height: GLOBAL.currentEnvironment ? '100vh' : 'calc(100vh - 1.12rem)',paddingBottom: GLOBAL.currentEnvironment ? '0.66rem' : ''}">
      <van-cell-group style="margin-top: 0.1rem">
        <p class="label required FormTit"><span></span>编号</p>
        <div class="haveUnitBox">
          <van-field v-model="buildForm.goodsCode" :maxLength='17' placeholder="请输入" @blur='checkInputValue(buildForm.goodsCode)' />
          <span class='btn-text' @click="genEntityCode">自动生成</span>
        </div>
        <div class="bottomLine"></div>
      </van-cell-group>
      <van-cell-group style="margin-top: 0.1rem">
        <p class="label required FormTit"><span></span>名称</p>
        <van-field v-model="buildForm.goodsName" placeholder="请输入" maxlength="30"/>
        <div class="bottomLine"></div>
      </van-cell-group>
      <van-cell-group style="margin-top: 0.1rem">
        <p class="label required FormTit"><span></span>类型</p>
        <van-field-select-picker :supportClear='true' label="" placeholder="请选择" v-model="buildForm.type" :columns="goodTypeList" :option="{ label: 'text', value: 'value' }" />
        <div class="bottomLine"></div>
      </van-cell-group>
      <van-cell-group>
        <p class="label required FormTit"><span></span>分类</p>
        <van-field readonly :is-link="!buildForm.categoryText" v-model="buildForm.categoryText" placeholder="请选择" @click="showTree = true">
        <div
            slot="right-icon"
            v-show="!!treeValue.categoryText"
            @click.stop="clickItem('')"
          >
            <img
              src="~@/assets/img/filedClear.png"
              alt=""
              style="width: 0.16rem"
            />
          </div>
        </van-field>
        <div class="bottomLine"></div>
      </van-cell-group>
      <van-cell-group>
        <p class="label required FormTit"><span></span>规格</p>
        <van-field v-model="buildForm.spec" placeholder="请输入" />
        <div class="bottomLine"></div>
      </van-cell-group>
      <van-cell-group>
        <p class="label required FormTit"><span></span>基本单位/生产单位</p>
        <van-field-select-picker :supportClear='true' label="" placeholder="请选择" v-model="buildForm.basicUnit" :columns="unitList" :option="{ label: 'text', value: 'value' }" />
        <div class="bottomLine"></div>
      </van-cell-group>
      <van-cell-group>
        <!-- <upload iconType="fj" titleName='商品图片' @fileChange="fileChange" :fileIds="buildForm.attachment" /> -->
        <fileSelector
          iconType="fj"
          :title="'商品图片'"
          @fileChange="fileChange"
          :fileIds="buildForm.attachment"
        ></fileSelector>
      </van-cell-group>
      <van-cell-group style='margin-top:0.1rem' v-if="!goodsAssistUnitList || !goodsAssistUnitList.length">
        <div class="">
          <div class="label otherText">辅助单位</div>
        </div>
        <div class="bottomLine"></div>
      </van-cell-group>
      <div class="reportBox" v-for="(item,index) in goodsAssistUnitList" :key="index">
        <van-cell-group style='margin-top:0.1rem'>
          <div class="goodTitleBox">
            <div class="label otherText">辅助单位({{index+1}})</div>
            <img class="buleDelete" @click="deleteGodd(index)" src="@/assets/img/delete.png" alt="">
          </div>
          <div class="bottomLine"></div>
        </van-cell-group>
        <van-cell-group>
          <p class="label required FormTit"><span></span>辅助单位</p>
          <van-field-select-picker :supportClear='true' label="" placeholder="请选择" v-model="item.assistUnit" :columns="unitList" :option="{ label: 'text', value: 'value' }" />
          <div class="bottomLine"></div>
        </van-cell-group>
        <van-cell-group>
          <p class="label required FormTit"><span></span>一辅助单位等于多少基本单位</p>
          <van-field v-model="item.conversionRate" placeholder="请输入" />
          <div class="bottomLine"></div>
        </van-cell-group>
        <van-cell-group>
          <p class="label required FormTit"><span></span>是否启用</p>
          <van-field-select-picker :supportClear='true' label="" placeholder="请选择" v-model="item.isUse" :columns="selectList" :option="{ label: 'text', value: 'value' }" />
          <div class="bottomLine"></div>
        </van-cell-group>
      </div>
      <van-cell-group>
        <div class="addBtnBox" @click="addGood">+添加</div>
      </van-cell-group>
      <van-cell-group style="margin-top: 0.1rem">
        <p class="label required FormTit"><span></span>预留采购时长（天）</p>
        <van-field v-model="buildForm.estimatePurchaseTime" placeholder="请输入" />
        <div class="bottomLine"></div>
      </van-cell-group>
      <div style="margin-top: 0.12rem" v-if="showExam">
        <Examine @submitProcess="submitProcess" @getUserState="getUserState" :type="appTitle==='新建物品'?'0':'1'" :key="examKey" id="WMS_GOODS" ref="examine" />
        <div style="height: 0.26rem"></div>
      </div>
      <div class="search-bottoms">
        <span class="btnconfirm" @click="btnConfirm">提交</span>
      </div>
    </div>
    <van-popup v-model="showTree" position="bottom">
      <div class="van-picker__toolbar">
        <button type="button" class="van-picker__cancel" @click="confirmTree">取消</button>
        <button type="button" class="van-picker__confirm" @click="confirmTree">确认</button>
      </div>
      <van-tree-select :items="categoryList" :active-id="treeValue.category" :main-active-index.sync="activeIndex" @click-item="clickItem" />
    </van-popup>
  </div>
</template>
<script>
import { getAction } from "@/api/manage";
import upload from "@/components/upload/upload";
import { clearNoNum, validateDuplicateValue, accAdd } from "@/utils/util";
import Navbar from "@/components/navBar/navBar_right";
import VanFieldSelectPicker from "@/components/ActionSheet/VanFieldSelectPicker";
import { goodsAdd, goodsEdit } from "@/api/mobile";
import { getDictModel, categoryGetTree } from "@/api/system.js";
import { APILX } from "@/api/requestLx";
import Examine from "@/components/examine";
import fileSelector from "@/components/fileSelector.vue";
export default {
  name: "search",
  components: {
    VanFieldSelectPicker,
    Navbar,
    upload,
    Examine,
    fileSelector
  },
  data() {
    return {
      activeIndex: 0,
      showTree: false,
      categoryList: [],
      showPeopleSlect: false,
      examKey: 1,
      //辅助单位
      goodsAssistUnitList: [
        {
          assistUnit: "",
          conversionRate: "",
          isUse: "",
        },
      ],
      buildForm: {
        goodsCode: "",
        goodsName: "",
        type: "",
        category: "",
        categoryText: "",
        spec: "",
        basicUnit: "",
        attachment: "",
        estimatePurchaseTime: "",
      },
      selectList: [
        { text: "是", value: "0" },
        { text: "否", value: "1" },
      ],
      goodTypeList: [],
      unitList: [],
      appTitle: "新建物品",
      parentId: "",
      showExam: true,
      selectedValue: {
        category: '',
        categoryText: ''
      },
      treeValue: {
        category: '',
        categoryText: ''
      }
    };
  },
  beforeRouteLeave(to, from, next) {
    if (this.showPeopleSlect) {
      this.$refs.examine.closePicker();
      next(false);
    } else {
      next();
    }
  },
  created() {
    this.parentId = this.$route.query.id;
    if (this.parentId) {
      this.appTitle = "编辑物品";
      this.showExam = false;
      APILX.goodsQueryById(this.parentId).then((res) => {
        if (res.code == 200) {
          let resObj = res.result;
          console.log("######", resObj);
          for (let k in this.buildForm) {
            this.buildForm[k] = resObj[k];
          }
          this.goodsAssistUnitList = resObj.goodsAssistUnitList;
        }
      });
    } else {
      this.showExam = true;
    }
    this.getInitData();
  },
  methods: {
    getUserState(v) {
      this.showPeopleSlect = v;
    },
    confirmTree() {
      if (this.categoryList[this.activeIndex].children.length == 0) {
          let v = this.categoryList[this.activeIndex]
          this.buildForm.categoryText = v.text;
          this.buildForm.category = v.id;
          this.treeValue.categoryText = v.text;
          this.treeValue.category = v.id;
        } else {
          this.buildForm.categoryText = this.treeValue.categoryText;
          this.buildForm.category = this.treeValue.category;
          this.treeValue.categoryText = this.treeValue.categoryText;
          this.treeValue.category = this.treeValue.category;
        }
        this.showTree = false;
        return
      if (!this.treeValue.category && this.categoryList.length > 0) {
        console.log(this.categoryList[this.activeIndex]);
        if (this.categoryList[this.activeIndex].children.length == 0) {
          let v = this.categoryList[this.activeIndex]
          this.buildForm.categoryText = v.text;
          this.buildForm.category = v.id;
          this.treeValue.categoryText = v.text;
          this.treeValue.category = v.id;
        } else {
          this.buildForm.categoryText = '';
          this.buildForm.category = '';
          this.treeValue.categoryText = '';
          this.treeValue.category = '';
        }
      } else {
        this.buildForm.categoryText = this.treeValue.categoryText;
        this.buildForm.category = this.treeValue.category;
        this.treeValue.categoryText = this.treeValue.categoryText;
        this.treeValue.category = this.treeValue.category;
      }
      this.selectedValue = {
        category: '',
        categoryText: ''
      }
      this.showTree = false;
    },
    clickItem(v) {
      if(!v){
      this.selectedValue.categoryText = '';
      this.selectedValue.category = '';
      this.treeValue.categoryText = '';
      this.treeValue.category = '';
      this.buildForm.categoryText = '';
      this.buildForm.category = '';
      return  
      }
      if (this.treeValue.category == v.id) {
        this.selectedValue.categoryText = '';
        this.selectedValue.category = '';
        this.treeValue.categoryText = '';
        this.treeValue.category = '';
      } else {
        this.selectedValue.categoryText = v.text;
        this.selectedValue.category = v.id;
        this.treeValue.categoryText = v.text;
        this.treeValue.category = v.id;
      }
    },
    deleteGodd(index) {
      this.goodsAssistUnitList.splice(index, 1);
    },
    addGood() {
      let goodObj = {
        assistUnit: "",
        conversionRate: "",
        isUse: "",
      };
      this.goodsAssistUnitList.push(goodObj);
    },
    genEntityCode() {
      getAction("/sys/common/genEntityCode", {
        entityCode: "WMS_GOODS",
      }).then((res) => {
        if (res.code == 200) {
          this.buildForm.goodsCode = res.result;
        } else {
          this.buildForm.goodsCode = "";
          this.$toast(res.message);
        }
      });
    },
    fileChange(ids) {
      this.buildForm.attachment = ids;
    },
    submitProcess(e) {
      if (e && e.nodeDtos) {
        // 获取到数据后写表单提交的方法
        this.handleSubmit(e);
      } else {
        // 调用子组件的方法获取数据
        this.$refs.examine.confirm();
      }
    },
    // 提交
    btnConfirm() {
      if (!this.buildForm.goodsCode) {
        this.$toast(`请输入编号`);
        return;
      }
      if (!this.buildForm.goodsName) {
        this.$toast(`请输入名称`);
        return;
      }
      if (!this.buildForm.type) {
        this.$toast(`请选择类型`);
        return;
      }
      if (!this.buildForm.category) {
        this.$toast(`请选择分类`);
        return;
      }
      if (!this.buildForm.spec) {
        this.$toast(`请输入规格`);
        return;
      }
      if (!this.buildForm.basicUnit) {
        this.$toast(`请选择基本单位/生产单位`);
        return;
      }
      for (let i = 0; i < this.goodsAssistUnitList.length; i++) {
        let item = this.goodsAssistUnitList[i];
        if (!item.assistUnit) {
          this.$toast(`辅助单位（${i + 1}），请选择辅助单位`);
          return;
        }
        if (item.conversionRate == "") {
          this.$toast(`出库商品（${i + 1}），请输入一辅助单位等于多少基本单位`);
          return;
        }
        if (item.isUse == "") {
          this.$toast(`出库商品（${i + 1}），请选择是否启用`);
          return;
        }
        if (!this.buildForm.estimatePurchaseTime) {
          this.$toast(`请输入预留采购时长`);
          return;
        }
      }
      if (!this.parentId) {
        this.submitProcess();
      } else {
        this.handleSubmit();
      }
    },

    handleSubmit(processDataVo) {
      let params = {
        ...this.buildForm,
        goodsAssistUnitList: this.goodsAssistUnitList,
      };
      if (!this.parentId) {
        params.processDataVo = processDataVo;
      }
      let commitApi = "";
      let successMeg = "";
      if (this.parentId) {
        params.id = this.parentId;
        commitApi = goodsEdit;
        successMeg = "物品编辑成功！";
      } else {
        commitApi = goodsAdd;
        successMeg = "物品创建成功！";
      }
      commitApi(params).then((res) => {
        if (res.success) {
          this.$toast(successMeg);
          this.$router.go(-1);
        } else {
          this.$toast(res.message);
        }
      });
    },
    checkInputValue(value) {
      validateDuplicateValue(
        "wms_goods",
        "goods_code",
        value,
        this.parentId,
        (res) => {
          if (res) {
            this.buildForm.goodsCode = "";
            this.$toast(res);
          }
        }
      );
    },
    getInitData() {
      // 类型字典
      getDictModel({ dictCode: "wms_goods_type" }).then((res) => {
        if (res.code == 200) {
          this.goodTypeList = res.result;
        }
      });
      // 取分类树
      categoryGetTree({ code: "B05" }).then((res) => {
        this.categoryList = res.result[0].children;
        if (this.categoryList.length > 0) {
          this.recursion(this.categoryList);
        }
      });
      // 基本单位
      getDictModel({ dictCode: "wms_goods_unit" }).then((res) => {
        this.unitList = res.result;
      });
    },
    recursion(newArray) {
      newArray.forEach((item) => {
        item.text = item.name;
        if (item.children.length > 0) {
          this.recursion(item.children);
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/theme.scss";
@import "@/views/workManagement/materialRequisition/materialForm.scss";
.search-content {
  //  padding-bottom: 0.5rem;
  position: fixed;
  top: 0.42rem;
  width: 100%;
  height: calc(100vh - 1rem);
  background: #f5f5f5;
  overflow: scroll;
  z-index: 99;
  .formgroup {
    background: #ffffff;
    // padding: 0 0.16rem;
    margin-top: 0.1rem;
    margin-bottom: 0.2rem;
    padding-top: 0.1rem;

    .title {
      width: 0.58rem;
      height: 0.14rem;
      font-size: 0.15rem;
      font-family: PingFang SC;
      font-weight: 400;
      color: #191f25;
      line-height: 0.05rem;
      margin-left: 0.16rem;
    }
  }
  .search-bottoms {
    width: 100%;
    height: 0.5rem;
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: fixed;
    bottom: 0px;
    padding: 0rem 0.11rem;
    box-sizing: border-box;
    font-size: 0.16rem;
    font-weight: 500;
    z-index: 9;
    .btnconfirm {
      flex: 1;
      background: #1890ff;
      box-sizing: border-box;
      height: 0.39rem;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 0.03rem;
      color: #ffffff;
    }
  }
}
.bottomLine {
  height: 0.01rem;
  background-color: #f0f0f0;
  margin: 0 0.16rem;
}
.otherText {
  font-size: 0.16rem;
  font-weight: bold;
  color: #191f25;
}
.haveUnitBox {
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  padding-right: 0.16rem;
  /deep/ .van-cell {
    padding-right: 0;
    width: 2.6rem;
  }
  /deep/ .van-field__control {
    max-width: 3rem;
  }
}
/deep/ .van-nav-bar {
  z-index: 99;
}
/deep/.van-sidebar-item--select::before {
  color: #1890ff;
  background-color: #1890ff;
}
/deep/.van-tree-select__item--active {
  color: #1890ff;
}
</style>
